package io.github.xxyopen.novel.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.github.xxyopen.novel.app.vo.ChatMemoryVo;
import io.github.xxyopen.novel.app.vo.OneChatMemoryVo;
import io.github.xxyopen.novel.core.auth.UserHolder;
import io.github.xxyopen.novel.core.common.resp.RestResp;
import io.github.xxyopen.novel.dao.entity.AiChatMemory;
import io.github.xxyopen.novel.service.AiChatMemoryService;
import io.github.xxyopen.novel.dao.mapper.AiChatMemoryMapper;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
* @author Administrator
* @description 针对表【ai_chat_memory】的数据库操作Service实现
* @createDate 2025-07-04 10:16:29
*/
@Service
public class AiChatMemoryServiceImpl extends ServiceImpl<AiChatMemoryMapper, AiChatMemory>
    implements AiChatMemoryService{

    @Override
    public RestResp<List<ChatMemoryVo>> getChatMemoryList() {
        Long userId = UserHolder.getUserId();
        List<AiChatMemory> aiChatMemories = lambdaQuery()
                .eq(AiChatMemory::getUserId, userId)
                .orderByDesc(AiChatMemory::getConversationId)
                .list();
        //根据conversation_id进行分组
        Map<String, List<AiChatMemory>> group = aiChatMemories.stream().collect(Collectors.groupingBy(AiChatMemory::getConversationId));
        List<ChatMemoryVo> chatMemoryVos = new ArrayList<>();
        group.forEach((k, v) -> {
            ChatMemoryVo chatMemoryVo = new ChatMemoryVo();
            chatMemoryVo.setChatId(k);
            String content = v.getFirst().getContent();
            chatMemoryVo.setTitle(content.substring(0, Math.min(content.length(), 10)));
            chatMemoryVos.add(chatMemoryVo);
        });
        return RestResp.ok(chatMemoryVos);
    }

    @Override
    public RestResp<List<OneChatMemoryVo>> getChatMemoryByChatId(String chatId) {
        Long userId = UserHolder.getUserId();
        List<AiChatMemory> list = lambdaQuery()
                .eq(AiChatMemory::getConversationId, chatId)
                .eq(AiChatMemory::getUserId, userId)
                .orderByAsc(AiChatMemory::getCreateTime)
                .list();

        List<OneChatMemoryVo> list1 = list.stream().map(aiChatMemory -> {
            OneChatMemoryVo oneChatMemoryVo = new OneChatMemoryVo();
            oneChatMemoryVo.setType(aiChatMemory.getType());
            oneChatMemoryVo.setContent(aiChatMemory.getContent());
            return oneChatMemoryVo;
        }).toList();
        return RestResp.ok(list1);
    }
}




